# -*- coding:utf-8 -*-
# 单线程写法
import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
}


class Put_Thread():
    def __init__(self):
        self.url = "https://sc.chinaz.com/tupian/index.html"

    # 构建翻页
    def get_url_list(self):
        url_list = []
        url_list.append(self.url)
        for num in range(2, 11):
            url_list.append("https://sc.chinaz.com/tupian/index_{}.html".format(num))
        return url_list

    # 向网站发起请求
    def get_data_index(self, url):
        response = requests.get(url, headers=headers)
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
        else:
            return None

    # 解析数据
    def parse_data(self, response):
        soup = BeautifulSoup(response, "lxml")
        data_list = soup.find_all("img", class_="lazy")
        for data in data_list:
            title = data.get("alt")
            href = "https:" + data.get("data-original").replace("_s", "")
            self.write_data(title, href)

    def write_data(self, title, href):
        with open("./image/" + title + ".jpg", "wb")as f:
            resp = requests.get(href).content
            f.write(resp)
            print(title, "保存成功")

    def main(self):
        url_list = self.get_url_list()
        for url in url_list:
            resp = self.get_data_index(url)
            self.parse_data(resp)


if __name__ == '__main__':
    thread = Put_Thread()
    thread.main()


# //scpic.chinaz.net/files/default/imgs/2023-09-21/effd45d38dbe26f5_s.jpg    -- 缩略图
# //scpic.chinaz.net/files/default/imgs/2023-09-21/effd45d38dbe26f5.jpg      -- 大图
